package com.finance.system.service;

import com.finance.system.dao.TableMapper;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by CBWL on 2017/5/17.
 */
@Service
public class TableService implements ITableService {
    @Autowired
    private TableMapper tableMapper;
    @Override
    public void createTable(String name, Map<String, String> columns,String primaryKey) {
        if(StringUtils.isBlank(name)) {
            throw new IllegalArgumentException("表名不可为空");
        }
        if(MapUtils.isEmpty(columns)) {
            throw new IllegalArgumentException("列表不可为空");
        }
        Iterator<Map.Entry<String,String>> it = columns.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<String,String> entry = it.next();
            String colName = entry.getKey();
            String colDefination = entry.getValue();
            if(StringUtils.isBlank(colName)) {
                throw new IllegalArgumentException("列名不可为空");
            }
            if(StringUtils.isBlank(colDefination)) {
                throw new IllegalArgumentException("列类型不可为空");
            }
        }
        this.tableMapper.createTable(name,columns,primaryKey);
    }

    @Override
    public void copyTable(String origin, String dest) {
        this.tableMapper.copyTable(origin,dest);
    }

    @Override
    public void createCommonIndex(String indexName, String tableName, String column, int length) {
        if(StringUtils.isBlank(tableName)) {
            throw new IllegalArgumentException("表名不可为空");
        }
        if(StringUtils.isEmpty(indexName)) {
            throw new IllegalArgumentException("索引不可为空");
        }
        if(StringUtils.isEmpty(column)) {
            throw new IllegalArgumentException("列名不可为空");
        }
        this.tableMapper.createCommonIndex(indexName,tableName,column,length);
    }

    @Override
    public void createUniqueIndex(String indexName, String tableName, String column, int length) {
        if(StringUtils.isBlank(tableName)) {
            throw new IllegalArgumentException("表名不可为空");
        }
        if(StringUtils.isEmpty(indexName)) {
            throw new IllegalArgumentException("索引不可为空");
        }
        if(StringUtils.isEmpty(column)) {
            throw new IllegalArgumentException("列名不可为空");
        }
        this.tableMapper.createUniqueIndex(indexName,tableName,column,length);

    }
}
